/**
 * @author banglong
 * @date 2016/8/22.
 */
define(['Layer', 'layPage', 'rootPath'], function (layer, laypage, rootPath) {

  var alterError = function (ex) {
    layer.msg(ex.message || ex, {
      icon: 5,
      offset: '90px'
    });
  };

  var alterInfo = function (ex) {
    layer.msg(ex.message || ex, {
      offset: '90px'
    });
  };

  var handleError = function (ex) {
    // 有两三种情况 第一种 简单的退出 Promise 不做任何处理
    if (ex === 'exit') {
      return;
    }
    // 第二种情况 session 过期 自动跳转到登录页面
    if (ex === '0') {
      layer.msg('您的会话已过期，请重新登录', {
        icon: 5,
        offset: '90px'
      });
      setTimeout(function () {
        location.href = 'login';
      }, 500);
      return;
    }
    // 第三种情况 输出错误信息
    alterError(ex);
  };

  // 获取第一个元素节点
  var getFirstElementChild = function (node) {
    if (node.firstElementChild) {
      return node.firstElementChild;
    }
    var childs = node.childNodes;
    for (var i = 0; i < childs.length; i++) {
      if (childs[i].nodeType === 1) {
        return childs[i];
      }
    }
  };

  // 初始化 vm
  var initAvalonVm = function (avalon, VmConfig, className, func) {
    delete avalon.vmodels[VmConfig.$id];
    if (avalon.scopes) {
      delete avalon.scopes[VmConfig.$id];
    }
    var vm = avalon.define(VmConfig);
    // vm.$watch('onReady', function () {
    // });
    // vm.$watch('onDispose', function () {
    //     delete avalon.vmodels[VmConfig.$id];
    //     if (avalon.scopes) {
    //         delete avalon.scopes[VmConfig.$id]
    //     }
    //     console.log('onDispose');
    // });
    avalon.scan(document.body);
    // avalon.scan(document.querySelector(className));
    return vm;
  };

  // 移除第一个节点并保存
  var removeFirstChildNode = function (main, documentNodeTree) {
    documentNodeTree[0] = main.removeChild(getFirstElementChild(main));
  };

  var initChildNode = function ($main, htmlTemp, className) {

    var isFirstInit = false;
    // 传过来的 className 标准格式为 '.ccccc' 所以需要截取掉第一个 .
    if ($main.find(className).length === 0 && !documentNodeTree[className.substr(1, className.length)]) {
      $main.append(htmlTemp);
      isFirstInit = true;
    }

    var main = $main.get(0);
    if (!isFirstInit) {
      var node = main.appendChild(documentNodeTree[className.substr(1, className.length)]);
      documentNodeTree[node.className] = node;
    }
  };

  // 计算 百分比
  var pxToPercent = function (c, p) {
    if (/\%/.test(c)) {
      return c;
    }
    return (c / p * 100).toFixed(2) + "%";
  };

  // 构建弹窗 otherParam 补充参数 用于解决 参数过长的问题
  var createNewOpenWindow = function (area, title, content, maxmin, otherParam) {
    otherParam = otherParam || {};
    var option = {
      type: 1,
      area: area,
      fix: false,
      closeBtn: 1,
      shade: typeof otherParam.shade !== 'undefined' ? otherParam.shade : 0.3,
      title: title,
      maxmin: maxmin,
      content: content,
      scrollbar: otherParam.scrollbar ? otherParam.scrollbar : false,
      end: function () {

        // 清空 avalon vm 中对应的对象
        if (otherParam && otherParam.vmConfig) {
          delete avalon.vmodels[otherParam.vmConfig.$id];
          if (avalon.scopes) {
            delete avalon.scopes[otherParam.vmConfig.$id];
          }
        }

        // 清空 table 组件中的数据
        if (otherParam && otherParam.vmConfig && otherParam.vmConfig.tableComponentsID) {
          otherParam.vmConfig.tableComponentsID.forEach(function (key) {
            delete avalon.vmodels[key];
            if (avalon.scopes) {
              delete avalon.scopes[key];
            }
          });
        }


        // 销毁方法
        if (otherParam && otherParam.destroy) {
          otherParam.destroy();
        }

        // ie 内存释放
        if (typeof CollectGarbage !== 'undefined') {
          CollectGarbage();
        }
      }
    };

    if (otherParam.offset) {
      option = Object.assign({}, option, {
        offset: otherParam.offset
      })
    }
    return layer.open(option);
  };

  // 高级定时器
  var throttle = function (obj, func, context) {
    clearTimeout(obj.tid);
    obj.tid = setTimeout(function () {
      func.call(context);
    }, 200);
  };

  // 分页工具
  var initPage = function (pageID, size, vm, vmArr, arr) {
    vm.pages = arr.length === 0 ? 0 : Math.ceil(arr.length / size);
    vm.count = arr.length;

    laypage({
      cont: pageID,
      pages: vm.pages,
      jump: function (obj, first) {
        //得到了当前页，用于向服务端请求对应数据
        var curr = obj.curr;
        var truePages = curr - 1;
        vmArr.splice(0, vmArr.length);
        // 此处进行两次 设置 chooseIndex的值 是为了方便触发 表格组件的 $watch 方法
        if (typeof vm.chooseIndex !== 'undefined') {
          vm.chooseIndex = 1;
        }
        vmArr.pushArray(arr.slice(truePages * size, truePages * size + size));
        if (typeof vm.chooseIndex !== 'undefined') {
          vm.chooseIndex = 0;
        }
      }
    });
  };

  var getElementAbsPos = function (e) {
    var t = e.offsetTop;
    var l = e.offsetLeft;
    while (e = e.offsetParent) {
      t += e.offsetTop;
      l += e.offsetLeft;
    }
    return {
      left: l,
      top: t
    };
  };

  var getEventTarget = function (e) {
    var target;
    if (e) {
      target = e.target;
    } else {
      target = window.event.srcElement;
    }
    return target;
  };

  var getEvent = function (e) {
    return e ? e : window.event;
  };

  // 获取滚动条的宽度和高度
  var getScrollBarWidth = function () {
    var __scrollBarWidth = null;
    return function () {
      if (__scrollBarWidth) return __scrollBarWidth;
      var scrollBarHelper = document.createElement("div");
      scrollBarHelper.style.cssText = "overflow:scroll;width:100px;height:100px;";
      document.body.appendChild(scrollBarHelper);
      if (scrollBarHelper) {
        __scrollBarWidth = {
          horizontal: scrollBarHelper.offsetHeight - scrollBarHelper.clientHeight,
          vertical: scrollBarHelper.offsetWidth - scrollBarHelper.clientWidth
        };
      }
      document.body.removeChild(scrollBarHelper);
      return __scrollBarWidth;
    };
  };

  // 获取游览器可视宽度和高度
  var getBrowserHeightAndWidth = function () {
    return {
      height: document.documentElement.clientHeight,
      width: document.documentElement.clientWidth
    }
  };

  var destroy = function (vmConfig) {
    // 清空 avalon vm 中对应的对象
    if (vmConfig) {
      delete avalon.vmodels[vmConfig.$id];
      if (avalon.scopes) {
        delete avalon.scopes[vmConfig.$id];
      }
    }

    // 清空 table 组件中的数据
    if (vmConfig.tableComponentsID) {
      vmConfig.tableComponentsID.forEach(function (key) {
        delete avalon.vmodels[key];
        if (avalon.scopes) {
          delete avalon.scopes[key];
        }
      });
    }

    // ie 内存释放
    $(document).unbind('destroy');
    if (typeof CollectGarbage !== 'undefined') {
      CollectGarbage();
    }
  };

  var bindDestroyMethod = function (destroy) {

    if (typeof destroy === 'function') {
      $(document).unbind('destroy');
      $(document).bind('destroy', function () {
        destroy();
      });
    }
  };

  var getYesterday = function () {
    return new Date((new Date()).valueOf() - 1000 * 60 * 60 * 24).format('yyyy-MM-dd'); // 昨天
  };

  var getTomorrow = function () {
    return new Date((new Date()).valueOf() + 1000 * 60 * 60 * 24).format('yyyy-MM-dd'); // 明天
  };

  // 判断相差时间是否大于 90 天
  var validateTime = function (start, end) {
    var month = 1000 * 3600 * 24 * 90;
    var date = new Date(end) - new Date(start);
    return date > month;
  };

  var getPos = function (el) {
    // yay readability
    for (var lx = 0, ly = 0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {
      lx: lx,
      ly: ly
    };
  };

  // 显示图片
  var showImg = function (event, picSrc, runtimeParam) {
    return function () {
      runtimeParam.showGoodsImg.find('img').attr('src', picSrc);
      var offset = getElementAbsPos(event.target);
      var top;
      if (event.clientY < 215) {
        top = offset.top + 5
      } else {
        top = offset.top - 205;
      }
      runtimeParam.showGoodsImg.css({
        left: offset.left + event.target.offsetWidth + 5,
        top: top
      });
      runtimeParam.showGoodsImg.show();
    }
  };

  // 显示图片的 dialog
  var showImgDialog = function (imgArray) {
    return function () {
      var liHtml = '<li data-target="#carousel-example-generic" data-slide-to="#{index}" class="active"></li>';
      var htmlTemp = $.ajax({
        url: rootPath.getRootPath() + "js/pages/html/components/common/imgDialog.html",
        async: false
      }).responseText;
      // 打开 dialog
      var layObj = createNewOpenWindow(['466px', '355px'], '图片预览', htmlTemp, null, {
        destroy: function () {
          // 弹窗销毁的时候的绑定事件
          $('body').unbind('keydown');
          $('body').on('keydown', function (e) {
            if (e.keyCode !== 27) return;
            layer.closeAll();
          });
        }
      });
      // 先解除 esc 键关闭所有弹窗的事件
      $('body').unbind('keydown')
      // 绑定关闭 事件
      var closeShowImgDialog = function (event) {
        event.stopPropagation();
        layer.close(layObj)
      }
      $('body').on('keydown', closeShowImgDialog)
      // carousel-indicators
      var carouselIndicators$ = $('.carousel-indicators');
      // carousel-inner
      var carouselInner$ = $('.carousel-inner');
      imgArray.forEach(function (src, index) {
        if(index < 10) {
            // 生成索引
            var liHtml = '<li data-target="#carousel-example-generic" data-slide-to="' + index +
              (index === 0 ? '" class="active">' : '">') + '</li>';
            // 生成img
            var imgHtml = (index === 0 ? '<div class="item active">' : '<div class="item">') +
              '<img src="' + src + '" alt="" style="height: 313px;">' + '</div>';
            carouselIndicators$.append(liHtml);
            carouselInner$.append(imgHtml);
        }
      })
    }
  }

  // ver 是游览器 版本号 6 - 9
  var isIE = function (ver) {
    var b = document.createElement('b');
    if (typeof ver === 'number') {
      b.innerHTML = '<!--[if IE ' + ver + ']><i></i><![endif]-->';
    } else {
      b.innerHTML = '<!--[if IE]><i></i><![endif]-->';
    }
    return b.getElementsByTagName('i').length === 1
  };

  // 通过 ActiveObject 对象来判断是否是 ie 游览器
  var isIEByActiveObject = function () {
    return !!window.ActiveXObject || "ActiveXObject" in window;
  };

  /*
   * options:{
   * url:‘‘,  //下载地址
   * data:{name:value}, //要发送的数据
   * method:‘post‘
   */
  var DownLoadFile = function (options) {
    var config = $.extend(true, {
      method: 'post'
    }, options);
    var $iframe = $('<iframe id="down-file-iframe" />');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
    $form.attr('action', config.url);
    for (var key in config.data) {
      $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
    }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
  };

  return {
    handleError: handleError,
    alterError: alterError,
    getFirstElementChild: getFirstElementChild,
    removeFirstChildNode: removeFirstChildNode,
    initChildNode: initChildNode,
    alterInfo: alterInfo,
    pxToPercent: pxToPercent,
    createNewOpenWindow: createNewOpenWindow,
    throttle: throttle,
    initPage: initPage,
    getElementAbsPos: getElementAbsPos,
    initAvalonVm: initAvalonVm,
    getEventTarget: getEventTarget,
    getEvent: getEvent,
    getScrollBarWidth: getScrollBarWidth,
    getBrowserHeightAndWidth: getBrowserHeightAndWidth,
    destroy: destroy,
    bindDestroyMethod: bindDestroyMethod,
    getYesterday: getYesterday,
    getTomorrow: getTomorrow,
    validateTime: validateTime,
    getPos: getPos,
    showImg: showImg,
    isIE: isIE,
    isIEByActiveObject: isIEByActiveObject,
    DownLoadFile: DownLoadFile,
    showImgDialog: showImgDialog
  };
});